package com.westar.tv;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.kyleduo.switchbutton.SwitchButton;
import com.westar.tv.utils.SharePreferencesUtils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ZWP on 2019/10/11 14:56.
 * 描述：
 */
public class SettingActivity extends ToolBarActivity {

    TextView tvUrl;
    SwitchButton ckBoot;
    RelativeLayout rlytActionUrl;
    String url_prefix;
    String url_suffix;

    TextView jumpBtn;
    TextView ipAddress;

    Runnable runnable;
    Handler handler;
    //倒计时数字
    private int TIME = 5;
    //倒计时步长 1秒
    private int TIME_INTERVAL = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        initId();
        initView();

        //获得焦点
        rlytActionUrl.requestFocus();

        ipAddress.setText(Html.fromHtml(String.format(getString(R.string.ip_address), getLocalIPAddress())));

        Intent intent = getIntent();
        boolean firstStart = intent.getBooleanExtra("firstStart", false);
        //第一次启动才显示计数
        if (firstStart) {
            timeTask();
        }
    }

    private void initId() {
        tvUrl = findViewById(R.id.tv_url);
        ckBoot = findViewById(R.id.ck_boot);
        rlytActionUrl = findViewById(R.id.rlyt_action_url);
        jumpBtn = findViewById(R.id.jump_btn);
        ipAddress = findViewById(R.id.ip_address);
        url_prefix = getString(R.string.url_prefix);
        url_suffix = getString(R.string.url_suffix);

        findViewById(R.id.btn_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (handler != null && runnable != null) {
                    //移除计时
                    handler.removeCallbacks(runnable);
                    //隐藏textview
                    jumpBtn.setVisibility(View.GONE);
                }
                app.appExit();
            }
        });

        ckBoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (handler != null && runnable != null) {
                    //移除计时
                    handler.removeCallbacks(runnable);
                    //隐藏textview
                    jumpBtn.setVisibility(View.GONE);
                }
                if (ckBoot.isChecked()) {
                    SharePreferencesUtils.put(SettingActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_BOOT, true);
                } else {
                    SharePreferencesUtils.put(SettingActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_BOOT, false);
                }
            }
        });

        rlytActionUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (handler != null && runnable != null) {
                    //移除计时
                    handler.removeCallbacks(runnable);
                    //隐藏textview
                    jumpBtn.setVisibility(View.GONE);
                }

                MaterialDialog dialog = new MaterialDialog.Builder(SettingActivity.this)
                        .title(R.string.dialog_title_url)
                        .customView(R.layout.dialog_txt_view, true)
                        .positiveText(R.string.action_ok)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                //保存设置
                                EditText urlInput = (EditText) dialog.getCustomView().findViewById(R.id.dialog_txt_input);
                                String url = urlInput.getText().toString();
                                SharePreferencesUtils.put(SettingActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SERVER_URL, url);
                                url = url_prefix + urlInput.getText().toString() + url_suffix;
                                tvUrl.setText(url);

                            }
                        }).build();

                String url = (String) SharePreferencesUtils.get(SettingActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SERVER_URL, Config.SERVER_URL);
                final View positiveAction = dialog.getActionButton(DialogAction.POSITIVE);
                if (!checkUrl(url)) {
                    positiveAction.setEnabled(false);
                }

                EditText urlInput = (EditText) dialog.getCustomView().findViewById(R.id.dialog_txt_input);
                urlInput.setText(url);
                urlInput.setSelection(urlInput.getText().length());
                urlInput.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (checkUrl(s.toString())) {
                            positiveAction.setEnabled(true);
                        } else {
                            positiveAction.setEnabled(false);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
                urlInput.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
                dialog.show();
            }
        });

        findViewById(R.id.rlyt_action_about).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (handler != null && runnable != null) {
                    //移除计时
                    handler.removeCallbacks(runnable);
                    //隐藏textview
                    jumpBtn.setVisibility(View.GONE);
                }
                Intent intent = new Intent(SettingActivity.this, AboutActivity.class);
                startActivity(intent);
            }
        });
    }


    /**
     * 倒计时
     */
    private void timeTask() {
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    if (TIME >= 0) {
                        jumpBtn.setVisibility(View.VISIBLE);
                        jumpBtn.setText(Html.fromHtml(String.format(getString(R.string.jump), TIME)));
                        handler.postDelayed(this, TIME_INTERVAL);
                        TIME--;//时间自减
                    } else {
                        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
                        intent.putExtra("startSetAct", false);
                        startActivity(intent);
                        SettingActivity.this.finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, TIME_INTERVAL); //每隔1s执行
    }


    @Override
    protected void onResume() {
        boolean landscape = (Boolean) SharePreferencesUtils.get(this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_LANDSCAPE, false);
        if (landscape) {
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
        super.onResume();
    }


    /**
     * 初始化视图
     */
    private void initView() {
        //地址
        String url = (String) SharePreferencesUtils.get(this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SERVER_URL, Config.SERVER_URL);
        url = url_prefix + url + url_suffix;
        tvUrl.setText(url);

        ckBoot.setChecked((Boolean) SharePreferencesUtils.get(this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_BOOT, false));
    }


    /**
     * 验证url
     *
     * @param url
     * @return
     */
    private boolean checkUrl(String url) {
//        Pattern p = Pattern.compile("(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", Pattern.CASE_INSENSITIVE);
        Pattern p = Pattern.compile("([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\\.)*([0-9a-zA-Z][0-9a-zA-Z]{0,61})?[0-9a-zA-Z]\\.[a-zA-Z]{2,6}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);
        return matcher.find();
    }

    /**
     * 获取ip地址
     *
     * @return
     */
    public static String getLocalIPAddress() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;

    }
}

